package org.example.shoppingsystem.controller;

import org.example.shoppingsystem.model.Product;
import org.example.shoppingsystem.service.ProductService;
import org.example.shoppingsystem.service.ProductServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.SQLException;
import java.util.List;

@Controller
public class ProductController {
    private ProductService productService = new ProductServiceImpl();

    @GetMapping("/products")
    public String showProducts(Model model) {
        try {
            List<Product> products = productService.findAllProducts();
            model.addAttribute("products", products);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "products";
    }

    @GetMapping("/addProduct")
    public String showAddProductPage() {
        return "addProduct";
    }

    @PostMapping("/addProduct")
    public String addProduct(@RequestParam("name") String name,
                             @RequestParam("price") Double price,
                             @RequestParam("category") String category,
                             Model model) {
        String errMsg = "";
        Product product = new Product();
        product.setName(name);
        product.setPrice(price);
        product.setCategory(category);

        try {
            if (productService.addProduct(product)) {
                return "redirect:/products"; // 添加成功，重定向到商品列表页面
            } else {
                errMsg += "商品名称已存在，请选择其他名称。";
            }
        } catch (SQLException e) {
            errMsg += "数据库操作出错，请稍后再试。";
            e.printStackTrace();
        }

        if (!errMsg.isEmpty()) {
            model.addAttribute("err", errMsg);
            return "addProduct"; // 添加失败，返回添加商品页面
        }
        return "addProduct";
    }
}